$(function () {
    $("#jqGrid").Grid({
        url: '../coupon/list',
        colModel: [
            {label: 'id', name: 'id', index: 'id', key: true, hidden: true},
            {label: '优惠券名称', name: 'name', index: 'name', width: 120},
            {label: '优惠金额', name: 'typeMoney', index: 'type_money', width: 80},
            {
                label: '发放方式', name: 'sendType', index: 'send_type', width: 80, formatter: function (value) {
                    if (value == 0) {
                        return '按订单发放';
                    } else if (value == 1) {
                        return '按用户发放';
                    } else if (value == 2) {
                        return '商品转发送券';
                    } else if (value == 3) {
                        return '按商品发放';
                    } else if (value == 4) {
                        return '新用户注册';
                    } else if (value == 5) {
                        return '线下发放';
                    } else if (value == 7) {
                        return '包邮优惠';
                    }
                    return '-';
                }
            },
            // {label: '最小金额', name: 'minAmount', index: 'min_amount', width: 80},
            {label: '开始优惠金额', name: 'maxAmount', index: 'max_amount', width: 80},
            {label: '自领取之日起有效天数', name: 'validityDays', index: 'validityDays', width: 80},
            // {
            //     label: '发放开始时间',
            //     name: 'sendStartDate',
            //     index: 'send_start_date',
            //     width: 120,
            //     formatter: function (value) {
            //         return transDate(value);
            //     }
            // },
            // {
            //     label: '发放结束时间', name: 'sendEndDate', index: 'send_end_date', width: 120, formatter: function (value) {
            //         return transDate(value);
            //     }
            // },
            // {
            //     label: '使用开始时间',
            //     name: 'useStartDate',
            //     index: 'use_start_date',
            //     width: 120,
            //     formatter: function (value) {
            //         return transDate(value);
            //     }
            // },
            {
                    label: '固定有效期结束时间', name: 'useEndDate', index: 'use_end_date', width: 100, formatter: function (value) {
                        return transDate(value);
                    }
                },
            {

                    label: '优惠券可领取结束时间', name: 'activityEndDate', index: 'activity_end_date', width: 100, formatter: function (value) {
                        return transDate(value);
                    }
                },
            // {
            //     label: '小程序是否显示', name: 'isShow',align:center,index: 'is_show', width: 80, formatter: function (value) {
            //         if (value == 0) {
            //             return '显示';
            //         } else if (value == 1) {
            //             return '不显示';
            //         }
            //     }
            // },
            // {label: '最小商品金额', name: 'minGoodsAmount', index: 'min_goods_amount', width: 80},
            {
                label: '操作', width: 70, sortable: false, formatter: function (value, col, row) {
                    if (row.sendType == 1 || row.sendType == 3) {
                        return '<button class="ivu-btn ivu-btn-primary ivu-btn-circle ivu-btn-small" onclick="vm.publish(' + row.id + ',' + row.sendType + ')"><i class="ivu-icon ivu-icon-android-send"></i>发放</button>';
                    }
                    return '';
                }
            }]
    });
});

var vm = new Vue({
    el: '#rrapp',
    data: {
        showList: true,
        showCard: false,
        showGoods: false,
        title: null,
        coupon: {sendType: 1,typeMoney:0,maxAmount:0,minAmount:0,minGoodsAmount:0,validityDays:0,validityType:2,isShow:1,discount:1},
        ruleValidate: {
            name: [
                {required: true, message: '优惠券名称不能为空', trigger: 'blur'}
            ],
            couponTypeId: [
                {required: true, message: '优惠券类型不能为空', trigger: 'change',type:'number'}
            ],
            typeMoney: [
                {required: true, message: '优惠面额不能为空', trigger: 'change',type:'number'}
            ],
            sendType: [
                {required: true, message: '发放方式不能为空', trigger: 'change',type:'number'}
            ],
            maxAmount: [
                {required: true, message: '满多少金额不能为空', trigger: 'change',type:'number'}
            ],
            validityType: [
                {required: true, message: '优惠券有效期不能为空', trigger: 'change',type:'number'}
            ],
            isShow: [
                {required: true, message: '是否显示不能为空.', trigger: 'change',type:'number'}
            ],
        },
        q: {
            name: ''
        },
        goods: [],
        goodss: [],
        user: [],
        users: [],
        selectData: {},
        sendSms: '',//是否发送短信
        assignGoods:[],
        tempUseStartDate:'',
        tempUseEndDate:'',
        activityStartDate:'', //优惠券活动开始时间
        activityEndDate:'', //优惠券活动结束时间
        selectedAssignGoods:null
    },
    mounted:function(){
        this.getAssignGoods()
    },
    methods: {
        query: function () {
            vm.reload();
        },
        add: function () {
            vm.showList = false;
            vm.showCard = true;
            vm.showGoods = false;
            vm.title = "新增";
            vm.coupon.sendType=0;
            vm.getGoodss()
        },
        update: function (event) {

            var id = getSelectedRow("#jqGrid");
            if (id == null) {
                return;
            }
            vm.showList = false;
            vm.showCard = true;
            vm.showGoods = false;
            vm.title = "修改";
            vm.goods=[];
            //获取商品数据
            vm.getGoodss();
            vm.getInfo(id)
        },
        handleStartTimeChange:function(time){
            vm.tempUseStartDate=time
        },
        handleEndTimeChange:function(time){
            vm.tempUseEndDate=time
        },
        handleActivityStartDate:function(time){
            vm.activityStartDate=time
        },
        handleActivityEndDate:function(time){
            vm.activityEndDate=time
        },
        handleGoodsChange:function(value){
            vm.selectedAssignGoods=value
        },
        getAssignGoods:function(){
            var params={limit:100,offset:1};
            var that=this;
            Ajax.request({
                type: "POST",
                url: '../coupon/queryAllGoods',
                contentType: "application/json",
                params: JSON.stringify(params),
                successCallback: function (r) {
                    if(r.code=='0'){
                        for(var key in r.goodsList){
                            that.assignGoods.push({
                                id: key,
                                name:r.goodsList[key]
                            })
                        }

                    }
                }
            });
        },
        saveOrUpdate: function (event) {

            var url = vm.coupon.id == null ? "../coupon/save" : "../coupon/update";
            //修复信息回显问题以及保存时候的验证问题
            vm.coupon.useStartDate=vm.tempUseStartDate;
            vm.coupon.useEndDate=vm.tempUseEndDate;

            if(vm.activityStartDate!=''){
                vm.coupon.activityStartDate=vm.activityStartDate;
            }
            if(vm.activityEndDate!=''){
                vm.coupon.activityEndDate=vm.activityEndDate;
            }


            if(vm.activityEndDate==''){
                vm.coupon.activityEndDate=null
            }
            if(vm.activityStartDate==''){
                vm.coupon.activityStartDate=null
            }
            if(vm.coupon.validityType==2){
                vm.coupon.validityDays=null;
                if(!vm.coupon.useStartDate){
                    alert('请选择使用开始时间');
                    return;
                }
                if(!vm.coupon.useEndDate){
                    alert('请选择使用结束时间');
                    return;
                }
            }else if(vm.coupon.validityType==1){
                vm.coupon.useStartDate=null;
                vm.coupon.useEndDate=null;
            }
            //日期格式转换
            //console.log(vm.coupon)
            //console.log(vm.selectedAssignGoods)
            // var params=vm.coupon.couponTypeId!='4'?JSON.stringify(vm.coupon):JSON.stringify({couponEntity:vm.coupon,goodsId:vm.selectedAssignGoods});
            //debugger
            var params=JSON.stringify({couponEntity:vm.coupon,goodsId:vm.selectedAssignGoods});
            var params=JSON.stringify({couponEntity:vm.coupon,goodsId:vm.goods});
            Ajax.request({
                type: "POST",
                url: url,
                contentType: "application/json",
                params: params,
                successCallback: function (r) {
                    alert('操作成功', function (index) {
                        vm.reload();
                    });
                }
            });
        },
        del: function (event) {
            var ids = getSelectedRows("#jqGrid");
            if (ids == null) {
                return;
            }
            //删除时后台进行一次查询，如果此优惠券已经被用户领取，优惠券就不能被删除。
            confirm('确定要删除选中的记录？', function () {
                Ajax.request({
                    type: "POST",
                    url: "../coupon/delete",
                    contentType: "application/json",
                    params: JSON.stringify(ids),
                    successCallback: function (r) {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    }
                });
            });
        },
        getInfo: function (id) {
            Ajax.request({
                url: "../coupon/info/" + id,
                async: true,
                successCallback: function (r) {
                    console.log(r.couponEntity,"修改相关信息回填")
                    vm.coupon = r.couponEntity;
                    vm.goods=r.couponGoodsId;
                }
            });
        },
        reload: function (event) {
            vm.showList = true;
            vm.showCard = false;
            vm.showGoods = false;
            var page = $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                postData: {'name': vm.q.name},
                page: page
            }).trigger("reloadGrid");
            vm.handleReset('formValidate');
        },
        handleSubmit: function (name) {
            handleSubmitValidate(this, name, function () {
                vm.saveOrUpdate()
            });
        },
        handleReset: function (name) {
            handleResetForm(this, name);
        },
        publish: function (id, sendType) {
            vm.showGoods = true;
            vm.goods = [];
            vm.user = [];
            vm.getGoodss();
            vm.getUsers();
            vm.selectData = {id: id, sendType: sendType};
            vm.sendSms = false;
            openWindow({
                title: "发放",
                area: ['600px', '350px'],
                content: jQuery("#sendDiv")
            })
        },
        getUsers: function () {
            Ajax.request({
                url: "../user/queryAll",
                async: true,
                successCallback: function (r) {
                    vm.users = r.list;
                }
            });
        },
        publishSubmit: function () {

            var sendType = vm.selectData.sendType;
            if (sendType == 1 && vm.user.length == 0) {
                vm.$Message.error('请选择下发会员');
                return;
            }
            if (sendType == 3 && vm.goods.length == 0) {
                vm.$Message.error('请选择下发商品');
                return;
            }
            confirm('确定下发优惠券？', function () {
                Ajax.request({
                    type: "POST",
                    dataType: 'json',
                    url: "../coupon/publish",
                    contentType: "application/json",
                    params: JSON.stringify({
                        sendType: vm.selectData.sendType,
                        couponId: vm.selectData.id,
                        goodsIds: vm.goods.toString(),
                        userIds: vm.user.toString(),
                        sendSms: vm.sendSms
                    }),
                    successCallback: function (r) {
                        layer.closeAll();  //关闭所有弹出层
                        vm.reload();
                        vm.showGoods = false;
                        vm.showList = true;
                    }
                });
            });
        },
        getGoodss: function () {
            Ajax.request({
                url: "../goods/queryAll/",
                async: true,
                successCallback: function (r) {
                    vm.goodss = r.list;

                }
            });
        }
    }
});
